﻿using db_manage.dll.db;
using db_manage.model;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace db_manage.dll.manage
{
    public partial class manage
    {
        /// <summary>
        /// 配置保存的文件
        /// </summary>
        private const string _db_manage_config_file_path = "db_manage_config.json";
        /// <summary>
        /// 配置数据
        /// </summary>
        private static db_config_manage _db_manage_config;
        public static db_config_manage db_manage_config
        {
            get
            {
                //第一次从文件读取配置
                if (_db_manage_config == null)
                {
                    if (File.Exists(_db_manage_config_file_path))
                    {
                        //从配置文件中读取数据
                        var config_str = System.IO.File.ReadAllText(_db_manage_config_file_path);
                        _db_manage_config = JsonConvert.DeserializeObject<db_config_manage>(config_str);
                    }
                    if (_db_manage_config == null)
                    {
                        _db_manage_config = new db_config_manage()
                        {
                            db_link_info = new List<db_link_info>(),
                            db_config_list = new db_config_list(),
                            db_config_exec = new db_config_exec(),
                            db_config_bak = new db_config_bak()
                        };
                    }
                }
                return _db_manage_config;
            }
            set
            {
                _db_manage_config = value;
                //将配置保存至文件
                var config_str = JsonConvert.SerializeObject(_db_manage_config);
                System.IO.File.WriteAllText(_db_manage_config_file_path, config_str);
            }
        }

        /// <summary>
        /// 窗口唯一
        /// </summary>

        private static readonly Dictionary<string, Form> dic_form = new Dictionary<string, Form>();
        public static T from_get<T>() where T : Form, new()
        {
            var tip = typeof(T).Name;
            if (!dic_form.ContainsKey(tip))
            {
                dic_form.Add(tip, new T());

            }
            else if (dic_form[tip].IsDisposed)
            {
                dic_form[tip] = new T();
            }
            return (T)dic_form[tip];
        }

        /// <summary>
        /// 数据库列表数据
        /// </summary>
        private static readonly List<db_info> _db_info_list = new List<db_info>();
        /// <summary>
        /// 获取数据库列表
        /// </summary>
        /// <param name="is_new">是否重新从数据库获取</param>
        /// <param name="is_total_cheked">是否全选</param>
        /// <returns></returns>
        public static List<db_info> db_info_list_get(bool is_new = false, bool is_total_cheked = false)
        {
            if (is_new || _db_info_list == null)
            {
                _db_info_list.Clear();
                db_manage_config.db_link_info.Where(x => x.is_check)
                                             ?.ToList()
                                             ?.ForEach(x =>
                                             {
                                                 var temp_list = db_factory.Instance.db_info_list(x);
                                                 if (temp_list?.Any() ?? false)
                                                 {
                                                     _db_info_list.AddRange(temp_list);
                                                 }
                                             });
                var db_config_list = db_manage_config.db_config_list;
                //过滤
                //-名称过滤
                if (!string.IsNullOrEmpty(db_config_list?.name_list))
                {
                    db_config_list.name_list = Regex.Replace(db_config_list.name_list, @"\s", "");
                    var name_list = db_config_list.name_list.Split(",");
                    _db_info_list.RemoveAll(x => !name_list.Contains(x.name));
                }
                if (!string.IsNullOrEmpty(db_config_list?.name_contains))
                {
                    db_config_list.name_contains = Regex.Replace(db_config_list.name_contains, @"\s", "");
                    var name_list = db_config_list.name_contains.Split(",");
                    _db_info_list.RemoveAll(x => !name_list.Any(y => x.name.Contains(y)));
                }
                if (!string.IsNullOrEmpty(db_config_list?.name_prefix))
                {
                    db_config_list.name_prefix = Regex.Replace(db_config_list.name_prefix, @"\s", "");
                    var name_list = db_config_list.name_prefix.Split(",");
                    _db_info_list.RemoveAll(x => !name_list.Any(y => x.name.StartsWith(y)));
                }
            }
            //编号
            var num = 0;
            _db_info_list?.ForEach(x =>
            {
                x.num = ++num;
                if (is_total_cheked)
                {
                    x.is_check = true;
                }
            });
            return _db_info_list;
        }

        /// <summary>
        /// 获取最后一条记录
        /// </summary>
        /// <param name="db_Info"></param>
        public static string last_get()
        {
            return manage.db_task(
                   new req_db_task()
                   {
                       exec_action = (db_Info) =>
                       {
                           var last = db_factory.Instance.last_get(db_Info);
                           if (last != null)
                           {
                               db_Info.vernum = last.vernum;
                               db_Info.updatetime = last.updatetime;
                               db_Info.sqlstr = last.sqlstr;
                               db_Info.remark = last.remark;
                               db_Info.taketime = last.taketime;
                               db_Info.updatestatus = last.updatestatus;
                           }
                           else
                           {
                               db_Info.remark = "没有记录";
                           }
                       }
                   });
        }

        /// <summary>
        /// 判断是否管理员权限
        /// </summary>
        /// <returns></returns>
        public static bool isAdmin()
        {
            System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();
            System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
            return principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator);
        }

        /// <summary>
        /// 设置执行结果
        /// </summary>
        public static void db_record_set(db_info db_info, bool is_success, string remark = null, Exception ex = null, string sqlstr = null)
        {
            db_info.updatestatus = is_success ? 1 : 0;
            db_info.remark = remark;
            db_info.sqlstr = sqlstr;
            if (string.IsNullOrEmpty(db_info.remark) && ex != null)
            {
                db_info.remark += $"异常：{ex.Message};{ (ex?.InnerException != null ? "内部异常：" + ex.InnerException.Message : "")}";
            }
            if (string.IsNullOrEmpty(db_info.remark) && is_success)
            {
                db_info.remark = "操作完成";
            }
            db_info.taketime = (DateTime.Now - (db_info.updatetime ?? DateTime.Now)).TotalMilliseconds;
        }

    }
}
